<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/23
 * Time: 16:32
 */

namespace app\api\controller\android\v13;


use jwt\Token;

use think\Controller;
use think\Exception;
use think\Request;
use redis\RedisPackage;
use app\api\model\Authority;


class Login extends Controller
{
    /**
     * @param array $data
     * @return array
     * $data=['id','name'=>'123']  id必填，name选填，默认值为123（有默认值时key不能为int）
     */
    public function post(array $data)
    {
        if (empty($data)) {
            r_date([], 300, '提交数据不正确');
        }
        $return = [];
        
        foreach ($data as $key => $item) {//key course_id item 1
            
            if (!is_int($key)) {
                $val = Request::instance()->post($key);
                
                if ($val != '') {
                    $return[$key] = trim($val);
                } else {
                    $return[$key] = trim($item);
                }
            } else {
                $val = Request::instance()->post($item);
                if (!isset($val)) {
                    r_date([], 300, "缺少 $item 数据");
                }
                $return[$item] = trim($val);
            }
        }
        return $return;
    }
    
    /**
     * 用户注册
     */
    public function register()
    {
        $data           = $this->post(['mobile', 'username', 'code', 'password', 'sex', 'age']);
        $data['avatar'] = "https://images.yiniao.co/static/images/avatar.jpg";
        if (!is_mobile($data['mobile'])) {
            r_date([], 300, '电话号码不符合规则');
        }
        if (!is_password($data['password'])) {
            r_date([], 300, '长度至少8位，必须包含字母与数字');
        }
        $redis    = new RedisPackage();
        $s_verify = $redis::get(md5($data['mobile']));
        if (empty($data['code']) || $data['code'] != $s_verify) {
            r_date([], 300, '验证码错误');
            
        }
        $redis::del(md5($data['mobile']));
        $data['password']       = encrypt($data['password']);
        $data['created_time']   = time();
        $data['device_id']   = 0;
        $data['status']         = 1;
        $data['originalmobile'] = $data['mobile'];
        $data['originalname']   = $data['username'];
        unset($data['code']);
        \db()->startTrans();
        try {
            $user_id = \db("user")->insertGetId($data);
            \db()->commit();
            r_date(['user_id' => $user_id], 200, '注册成功');                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
        } catch (Exception $e) {
            \db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }
        
    /**
     * 重置密码
     */
    public function reset_password()
    {
        $data = $this->post(['mobile', 'code', 'password']);
        if (!is_password($data['password'])) {
            r_date(null, 300, '长度至少8位，必须包含字母与数字');
        }
       
        $redis    = new RedisPackage();
        $s_verify = $redis::get(md5($data['mobile']));
        if (empty($data['code']) || $data['code'] != $s_verify) {
            r_date(null, 300, '验证码错误');
        }
        $redis::del(md5($data['mobile']));
        $user = db('user')
            ->where(['mobile' => $data['mobile']])
            ->find();
        if (!$user) {
            r_date(null, 300, '该手机号未注册');
        }
        $res = db('user')->where(['mobile' => $data['mobile']])->update(['password' => encrypt($data['password'])]);
        if ($res !== false) {
            r_date();
        }
        r_date(null, 300, '修改失败，请刷新后重试');
    }
    
    /*
     * 用户选择
     */
    public function UserSelect()
    {
        $data     = Request::instance()->post();
        if(!isset($data['mobile']) || empty($data['mobile'])){
            r_date(null, 300, '请输入手机号');
        }
      
        $userList = [
            'mobile|username' => trim($data['mobile']),
        ];
        if (isset($data['type']) && $data['type'] == 2) {
            $redis    = new RedisPackage();
            $s_verify = $redis::get(md5($data['mobile']));
            if (empty($data['code']) || $data['code'] != $s_verify) {
                r_date(null, 300, '验证码错误');
            }

            $redis::del(md5($data['mobile']));
            
        } else {
            $userList['password'] = encrypt($data['password']);
            if (!is_password($data['password'])) {
                r_date(null, 300, '长度至少8位，必须包含字母与数字,请在登录页面忘记密码重置密码');
            }
        }
        $user = db('user')
                ->field('user.user_id,user.username,user.mobile,st.store_name,user.universal,user.sales_or_deliverer as deliverer,user.status,user.in_business')
                ->join('store st', 'user.store_id=st.store_id', 'left')
                ->order('user.user_id desc')
                ->where($userList)
                ->select();
            if (!$user) {
                r_date(null, 300, '账号或密码错误');
            }
            
        if ($user[0]['universal'] == 1) {
            $userArray = db('user')
                ->field('user.user_id,if(user.sales_or_deliverer=1,concat(user.username,"(销售)"),concat(user.username,"(交付)")) as username,user.mobile,st.store_name,user.universal,user.sales_or_deliverer as deliverer,user.status,user.in_business')
                ->join('store st', 'user.store_id=st.store_id', 'left')
                ->where([
                    'user.status' => 0])
                ->select();
              
            foreach ($userArray as $k => $item) {
                $userArray[$k]['universal'] = $user[0]['universal'];
            }
            $user = array_merge($user, $userArray);
        }
        foreach($user as  &$item){
            if(empty($item['store_name'])){
                $item['store_name']="未配置店铺";
            }
             if($item['status']==1){
                $item['store_name']="待审核";
            }
            if($item['in_business']==2){
                $item['username']=$item['username']."(大改)";
            }
            if($item['in_business']==3){
                $item['username']=$item['username']."(小改)";
            }
        }
        r_date($user, 200, '操作成功');
    }
    
    /**
     * 登录
     */
    public function login()
    {
        $data  = $this->post(['user_id', 'phone']);
        $datas = Request::instance()->post();
        $user  = db('user')
            ->field('user.user_id,user.mobile,user.username,user.avatar,user.sex,user.access_token,st.store_name,user.reserve,user.sales_or_deliverer as deliverer,user.status,user.in_business as business')
            ->join('store st', 'user.store_id=st.store_id', 'left')
            ->where(['user_id' => $data['user_id']])
            ->find();

        if ($user['status'] == 1) {
            r_date(null, 300, '请等待审核');
        }
        if ($user['status'] == 2) {
            r_date(null, 300, '该用户已冻结');
        }
        $user['mobile'] = trim($user['mobile']);
        $user_name = $user['username'];
        $objToken = new Token;
        $token_data = [
            'user_id'   => $user['user_id'],
        ];
        $token_res = $objToken->createToken($token_data, 604800);
        if ($token_res['status'] == 200) {
            $access_token = $token_res['token'];
        } else {
            r_date(null, 300, '登录错误请稍候再试');
        }
        $universal  = db('user')->where(['mobile' => $data['phone']])->where('universal', 1)->find();

        $userInfo = ['last_login_time' => time(), 'access_token' => $access_token, 'device_id' => isset($datas['uuid']) ? $datas['uuid'] : 0, 'registrationId' => isset($datas['registrationId']) ? $datas['registrationId'] : ''];
        if (!empty($universal) && $data['phone'] !=$user['mobile']) {
            $user_name = $universal['username'] . '用万能账号登录了' . $user['username'] . '的账号';
            if (!empty($user['access_token'])) {
                unset($userInfo['access_token']);
            }
            unset($userInfo['registrationId']);
            $access_token = $user['access_token'];
        }
        $res = db('user')->where(['user_id' => $user['user_id']])->update($userInfo);
        if ($res !== false) {
            $accesstoken = request()->header("accesstoken");
            if (!empty($accesstoken) && !empty($datas['oldToken']) && $accesstoken != $access_token && empty($universal)) {
                $beforeRes = db('user')->where(['access_token' => $accesstoken])->find();
                $user_name = $beforeRes['username'] . '切换了' . $user['username'] . '的账号';
            }
            $user['access_token'] = $access_token;
            $user['universal'] = isset($datas['universal']) ? $datas['universal'] : 0;

            $user['phone'] = trim($data['phone']);
            $user['cityId'] = config('cityId');

            db('user_login_log', config('database.zong'))->insert(['role' => 6, 'user_id' => $data['user_id'], 'user_name' => $user_name, 'login_time' => time()]);
            r_date($user, 200);
        }
        r_date(null, 300, '请刷新后登录');
    }
    
    /**
     * 发送验证码
     */
    public function send_code()
    {
        $data = $this->post(['mobile']);
        $user = db("user")->where(['mobile' => $data['mobile']])->find();
//        if ($user) {
//            if ($user['status'] != 3) {
//                r_date([], 300, '该手机号已经注册');
//            }
//        }
        
        
        $code     = trim(mt_rand(100000, 999999));
        $redis    = new RedisPackage();
        $s_verify = $redis::set(md5($data['mobile']), $code);
        try {
            sendMsg($data['mobile'], 1, [$code]);
            r_date('[]', 200, '发送成功');
        } catch (Exception $e) {
            r_date([], 300, $e->getMessage());
        }
    }
    
    /**
     * 发送验证码
     */
    public function send_code1()
    {
        $data = $this->post(['mobile']);
        $user = db("user")->where(['mobile' => $data['mobile']])->find();
        if (!$user) {
            r_date([], 300, '该手机号未注册，无法登录');
        }
        
        $code  = trim(mt_rand(100000, 999999));
        $redis = new RedisPackage();
        $redis::set(md5($data['mobile']), $code);
        
        try {
            sendMsg($data['mobile'], 1, [$code]);
            r_date([], 200, '发送成功');
        } catch (Exception $e) {
            r_date([], 300, $e->getMessage());
        }
    }
    
    
    /***
     *
     * 退出
     *
     */
    public function logout()
    {
        $model     = new Authority();
        $user      = $model->check(1);
        $datas     = Request::instance()->post();
        $universal = isset($datas['universal']) ? $datas['universal'] : 0;
        if ($universal == 0) {
            $info = [
                'access_token' => '',
                'lat' => '',
                'lng' => '',
            ];
            $res  = db('user')
                ->where(['user_id' => $user['user_id']])
                ->update($info);
            if (!$res) {
                r_date(null, 300, '退出失败');
            }
        }
        
        r_date(null, 200, '退出成功');
        
    }
    /**
     * 店长接单弹窗
     */
    public function orderPopUpWindow()
    {
       
        $access_token = request()->header("accesstoken");
        $list=[];
        if (!empty($access_token)) {
            $objToken = new Token;
            $TokenList = $objToken->checkToken($access_token);

            if ($TokenList['status'] == 103 || $TokenList['status'] == 101) {
                r_date(null, 200, '登录已过期，请重新登录');
            }
            if ($TokenList['status'] == 199) {
                r_date(null, 200, '登录已过期，请重新登录');
            }
            if ($TokenList['status'] == 200) {
                $access_token = $TokenList['data']['data']->user_id;
                $user_id = $access_token;
                $list = db('order_dispatch_user_auto', config('database.zong'))
                    ->field('order_dispatch_user_auto.id,if(a.hardbound=0,concat(go.title,"-",go1.title,"-",go2.title),concat(go.title,"-",go1.title,"-",go2.title,"(精装房)")) as title,concat(c.city,u.county,a.addres) as addres, 
            order_dispatch_user_auto.user_limit_time as userLimitTime,
        case 
            when a.visiting_time = 1 then "尽快" 
            when a.visiting_time = 2 then "三天内" 
            when a.visiting_time = 3 then "七天内" 
            when a.visiting_time = 4 then "不着急" 
            else "" 
         end as visitingTime')
                    ->join('order a', 'a.order_id=order_dispatch_user_auto.order_id', 'left')
                    ->join('city c', 'a.city_id=c.city_id', 'left')
                    ->join('county u', 'a.county_id=u.county_id', 'left')
                    ->join('goods_category go', 'a.pro_id=go.id', 'left')
                     ->join('goods_category go1', 'a.pro_id1=go1.id', 'left')
                      ->join('goods_category go2', 'a.pro_id2=go2.id', 'left')
                    ->where('order_dispatch_user_auto.user_id', $user_id)
                    ->where('order_dispatch_user_auto.status', 1)
                    ->where('order_dispatch_user_auto.user_limit_time', ">=", time())
                    ->order('create_time desc')
                    ->find();
            }
        }

        r_date(empty($list) ? null : $list, 200);
    }
    
    
}